package com.javasearch.search;

import com.javasearch.Config;
import com.javasearch.MainApplication;
import com.javasearch.index.IndexEnum;
import com.javasearch.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class JavaSearch {
    private static final Logger logger = LoggerFactory.getLogger(JavaSearch.class);
    private static final String tempPath = FileUtil.getTempDirectoryPath() + IndexEnum.JAVAPATH.getIndexName() + File.separator + IndexEnum.JAVAPATH.getIndexName() + ".txt";

    public static void textSearch(String keyWord, String path, StringBuffer sb, Config config) {
        try {
            StringBuilder sb1 = new StringBuilder();
            AtomicInteger i = new AtomicInteger(0);
            File file = new File(path);
            try {
                ReadFileLineUtil.readFileStrLine(file, (line) -> {
                    i.getAndIncrement();
                    //跳过空行
                    if (line.trim().isEmpty()) {
                        return;
                    }
                    if (line.contains(keyWord)) {
                        synchronized (config) {
                            Integer searchLimit = config.getSearch().getSearchLimit();
                            if (searchLimit == 0) {
                                throw new SearchMaxLimitException("JarSourcesSearch搜索已达到上限");
                            }
                            config.getSearch().setSearchLimit(searchLimit - 1);
                        }
                        sb1.append("[text]##").append("[").append(path).append("]").append("##").append("[").append(i).append("]").append("##").append("[").append(line).append("]").append("\n");
                    }
                });
            } catch (SearchMaxLimitException e) {

            }
            sb.append(sb1);
        } catch (Exception e) {
            logger.error("JavaSearch Error textSearch ", e);
        }
    }


    public static void search(Config config) {
        String searchPath = config.getSearch().getSearchPath();
        File file = new File(tempPath);
        if (!file.exists()) {
            logger.info("java文件缓存不存在,请先执行索引");
            return;
        }
        String keyWord = config.getSearch().getSearchKey();
        StringBuffer sb = new StringBuffer();
        List<Future<?>> list = new ArrayList<>();
        try {
            ReadFileLineUtil.readFileStrLine(file, (path) -> {
                synchronized (config) {
                    Integer searchLimit = config.getSearch().getSearchLimit();
                    if (searchLimit == 0) {
                        throw new SearchMaxLimitException("JavaSearch搜索已达到上限");
                    }
                }
                Future<?> jar2 = MainApplication.executor.submit(() -> {
                    textSearch(keyWord, path, sb, config);
                });
                list.add(jar2);
            });
        } catch (SearchMaxLimitException e) {

        }
        ExecutorUtils.waitComplete(list);
        //将搜索结果写入文件
        WriteFileStrUtil.writeStrLock(new File(searchPath), sb.toString(), true);
        logger.info("JavaSearch-搜索结果:\n{}", sb);

    }
}
